package com.wfy.orchestra.dispatch.lifecycle

import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import com.wfy.orchestra.dispatch.DefaultTaskGraph
import com.wfy.orchestra.thread.ITaskExecutor
import com.wfy.orchestra.thread.MainThreadExecutor
import com.wfy.orchestra.thread.PoolTaskExecutor

/**
 * @author : wangfengyuan
 * e-mail  : 446950883@qq.com
 * time    : 2025/3/19
 * desc    :
 * version : 1.0
 */
class LifecycleTaskGraph(
    defaultExecutor: ITaskExecutor = PoolTaskExecutor(),
    mainExecutor: ITaskExecutor = MainThreadExecutor()
) : DefaultTaskGraph(defaultExecutor, mainExecutor), DefaultLifecycleObserver {
    private var lifecycle: Lifecycle? = null // 生命周期监听

    // 绑定到 LifecycleOwner（如 Activity/Fragment）
    fun bindToLifecycle(lifecycle: Lifecycle) {
        this.lifecycle = lifecycle
        lifecycle.addObserver(this)
    }

    // 当生命周期销毁时自动取消任务
    override fun onDestroy(owner: LifecycleOwner) {
        super.onDestroy(owner)
        lifecycle?.removeObserver(this)
        lifecycle = null
        cancelAll()
    }
}